#coding:utf-8
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseServerError
from django.views.decorators.csrf import csrf_protect
import pymongo
import hashlib
import redis
import time
import json
import re
import sys
import os

reload(sys)
sys.setdefaultencoding('utf8')
from config.tdm_config import *
from utils import *
from alert.alert_daemon import client_send
from acard.acard_utils import *
import config.tdm_mongo_modules as tmm
from datetime import datetime, date


'''
------------------------------------------------------------------------------
[PAGE] index, index page redirect to login
------------------------------------------------------------------------------
'''
def view_tdm_index(request):
    return HttpResponseRedirect('/tdm/login')


'''
------------------------------------------------------------------------------
[PAGE] login, login web page
------------------------------------------------------------------------------
'''
@csrf_protect
def view_tdm_login(request):
    r = redis.Redis(host=tdm_redis_host, db=tdm_redis_db)
    errors = []
    result = []

    # cookies login
    login_ret, user_name, user_role = check_user_in_cookie(r, request, tdm_user_role_admin)
    if login_ret == True:
        return HttpResponseRedirect('/tdm/main')

    tmm.db_connect(tdm_mongo_acard_db)

    # form login
    #print request.POST.items()
    if request.method == 'POST':
        if "username" in request.POST and "password" in request.POST:
            username = request.POST.get("username")
            password = request.POST.get("password")
            remember = request.POST.get("remember")
            login_tm = int(time.time() * 1000)
            print username, password, remember, login_tm

            user = tmm.TdmUser.objects(name=username).first()
            if user and user.passwd_md5 == hashlib.md5(password).hexdigest():
                # update the user lastlogin timestamp
                user.lastlogin_tm = datetime.now()
                user.save()
                # make a user login cache in redis
                # key = tdm:user:qujianning
                # val = admin,1438310975786
                # ttl = 300
                user_key = '%s:%s' % (tdm_redis_key_user, user.name)
                user_info = "%s,%s" % (user.grant, login_tm)
                r.set(user_key, user_info, ex=tdm_user_online_tm)
                response = HttpResponseRedirect('/tdm/main')
                response.set_cookie("tdm_user", username, 3600)
                return response
            else:
                errors.append("用户名或密码错误，请重新输入")
        else:
            errors.append("请输入用户名和密码")

    # anything else
    return render_to_response('tdm_server_login_template.html', locals(), context_instance=RequestContext(request))


'''
------------------------------------------------------------------------------
[PAGE] logout, logout web page
------------------------------------------------------------------------------
'''
def view_tdm_logout(request):
    r = redis.Redis(host=tdm_redis_host, db=tdm_redis_db)
    response = HttpResponseRedirect('/tdm/main')
    user_name = request.COOKIES.get("tdm_user", '')
    user_key = '%s:%s' % (tdm_redis_key_user, user_name)
    r.delete(user_key)
    response.delete_cookie("tdm_user")
    return response


'''
------------------------------------------------------------------------------
[PAGE] profile web page
------------------------------------------------------------------------------
'''
def view_tdm_profile(request):
    r = redis.Redis(host=tdm_redis_host, db=tdm_redis_db)
    errors = []
    result = []

    # cookies login
    login_ret, user_name, user_role = check_user_in_cookie(r, request, tdm_user_role_admin)
    #print login_ret, user_name, user_role
    if login_ret == False:
        return HttpResponseRedirect('/tdm/login')

    tmm.db_connect(tdm_mongo_acard_db)
    user_obj = tmm.TdmUser.objects(name=user_name).first()
    if not user_obj:
        return HttpResponseRedirect('/tdm/login')

    op = request.POST.get('op')
    if op == 'user_profile':
        new_email = request.POST.get('email','').encode('utf-8').strip()
        new_phone = request.POST.get('phone','').encode('utf-8').strip()
        new_passwd = request.POST.get('password').encode('utf-8').strip()

        user_obj.passwd_md5 = hashlib.md5(new_passwd).hexdigest()
        user_obj.email = new_email
        user_obj.phone = new_phone
        user_obj.save()
        result.append("修改用户成功")

    nav_page = "profile"
    return render_to_response('tdm_view_profile_template.html', locals(), context_instance=RequestContext(request))


'''
------------------------------------------------------------------------------
[PAGE] TDM main web page
------------------------------------------------------------------------------
'''
def view_tdm_main(request, city='all'):
    r = redis.Redis(host=tdm_redis_host, db=tdm_redis_db)
    errors = []
    result = []

    # cookies login
    login_ret, user_name, user_role = check_user_in_cookie(r, request, tdm_user_role_admin)
    print login_ret, user_name, user_role
    if login_ret == False:
        return HttpResponseRedirect('/tdm/login')

    #connect the database
    tmm.db_connect(tdm_mongo_acard_db)

    user_obj = tmm.TdmUser.objects(name=user_name).first()
    if not user_obj:
        return HttpResponseRedirect('/tdm/login')

    if city == 'all':
        city_summary_list = []
        #city_all = tmm.City.objects().order_by('zipcode')
        city_all = user_obj.station
        #module_all = tmm.TdmModule.objects()
        for city_i in sorted(city_all, key=lambda c:c.zipcode):
            city_summary = {}
            city_summary['obj'] = city_i
            city_summary['name'] = city_i.name
            city_summary['venues_nr'] = len(city_i.venues)
            #city_summary['server_nr'] = len(city_get_server_list(r, city_i))
            #city_summary['item_nr'] = len(city_get_server_item_list(r, city_i))
            city_summary['ctmdev_nr'] = sum([len(v.ctm_devs) for v in city_i.venues])
            city_summary['cardreader_nr'] = acard_get_cardreader_by_city(r, city_i.name)
            city_summary['power_warn_nr'] = 0
            city_summary['power_alert_nr'] = 0
            city_summary['network_warn_nr'] = city_get_module_warn_nr(r, 'network', city_i.name)
            city_summary['network_alert_nr'] = city_get_module_alert_nr(r, 'network', city_i.name)
            city_summary['server_warn_nr'] = city_get_module_warn_nr(r, 'server', city_i.name)
            city_summary['server_alert_nr'] = city_get_module_alert_nr(r, 'server', city_i.name)
            city_summary['mdm_warn_nr'] = 0
            city_summary['mdm_alert_nr'] = 0
            city_summary['acard_warn_nr'] = city_get_module_warn_nr(r, 'acard', city_i.name)
            city_summary['acard_alert_nr'] = city_get_module_alert_nr(r, 'acard', city_i.name)
            city_summary['acard_attend_yewu'] = acard_get_data_yewu(r, city_i)
            city_summary['acard_attend_core'] = acard_get_data_core(r, city_i)
            city_summary['acard_attend_ctm'] = acard_get_data_ctm(r, city_i)
            city_summary['data_success'] = (city_summary['acard_attend_yewu'] == city_summary['acard_attend_core'] == city_summary['acard_attend_ctm'])
            city_summary_list.append(city_summary)
    else:
        city = city.encode('utf-8')
        venue_summary_list = []
        view_city = tmm.City.objects(name=city).first()
        if not view_city in user_obj.station:
            errors.append('您没有权限访问这个页面')
            return render_to_response('tdm_view_error_template.html', locals(), context_instance=RequestContext(request))
        if view_city:
            for venue_i in view_city.venues:
                if venue_i.disabled:
                    continue
                venue_summary = {}
                venue_summary['obj'] = venue_i
                venue_summary['name'] = venue_i.name
                venue_summary['power_warn_nr'] = 0
                venue_summary['power_alert_nr'] = 0
                venue_summary['network_warn_nr'] = venue_get_module_warn_nr(r, 'network', city, venue_i.name)
                venue_summary['network_alert_nr'] = venue_get_module_alert_nr(r, 'network', city, venue_i.name)
                venue_summary['server_warn_nr'] = venue_get_module_warn_nr(r, 'server', city, venue_i.name)
                venue_summary['server_alert_nr'] = venue_get_module_alert_nr(r, 'server', city, venue_i.name)
                venue_summary['mdm_warn_nr'] = 0
                venue_summary['mdm_alert_nr'] = 0
                venue_summary['acard_warn_nr'] = venue_get_module_warn_nr(r, 'acard', city, venue_i.name)
                venue_summary['acard_alert_nr'] = venue_get_module_alert_nr(r, 'acard', city, venue_i.name)
                venue_summary['acard_attend_core'] = acard_get_venue_data_core(r, view_city, venue_i)
                venue_summary['acard_attend_ctm'] = acard_get_venue_data_ctm(r, view_city, venue_i)
                venue_summary['data_success'] = (venue_summary['acard_attend_core'] == venue_summary['acard_attend_ctm'])
                venue_summary_list.append(venue_summary)

    nav_page = "main"
    return render_to_response('tdm_view_main_template.html', locals(), context_instance=RequestContext(request))


'''
------------------------------------------------------------------------------
[PAGE] power item web page
------------------------------------------------------------------------------
'''
def view_power_item(request, city='all', venue='all', dev='all'):
    r = redis.Redis(host=tdm_redis_host, db=tdm_redis_db)
    errors = []
    result = []

    # cookies login
    login_ret, user_name, user_role = check_user_in_cookie(r, request, tdm_user_role_admin)
    print login_ret, user_name, user_role
    if login_ret == False:
        return HttpResponseRedirect('/tdm/login')
        
    #connect the database
    tmm.db_connect(tdm_mongo_acard_db)

    user_obj = tmm.TdmUser.objects(name=user_name).first()
    if not user_obj:
        return HttpResponseRedirect('/tdm/login')

    #get the city/jxd list
    city = city.encode('utf-8')
    venue = venue.encode('utf-8')
    dev = dev.encode('utf-8')
    #print [city, venue, ctmdev]

    #city_all = tmm.City.objects().order_by('zipcode')
    city_all = sorted(user_obj.station, key=lambda c:c.zipcode)
    if city == 'all':
        view_city = city_all[0] if len(city_all) > 0 else None
    if not city == 'all':
        view_city = tmm.City.objects(name=city).first()

    if not view_city in city_all:
        errors.append('您没有权限访问这个页面')
        return render_to_response('tdm_view_error_template.html', locals(), context_instance=RequestContext(request))

    view_venue = view_city.venues[0]
    if not venue == 'all':
        view_venue = tmm.Venue.objects(name=venue).first()
    pwrdev_list = view_venue.power_devs

    nav_page = "power"
    return render_to_response('tdm_view_power_template.html', locals(), context_instance=RequestContext(request))


'''
------------------------------------------------------------------------------
[PAGE] server view web page
------------------------------------------------------------------------------
'''
def view_server_item(request, city='all', venue='all', dev='all'):
    r = redis.Redis(host=tdm_redis_host, db=tdm_redis_db)
    errors = []
    result = []

    # cookies login
    login_ret, user_name, user_role = check_user_in_cookie(r, request, tdm_user_role_admin)
    print login_ret, user_name, user_role
    if login_ret == False:
        return HttpResponseRedirect('/tdm/login')

    #connect the database
    tmm.db_connect(tdm_mongo_acard_db)

    user_obj = tmm.TdmUser.objects(name=user_name).first()
    if not user_obj:
        return HttpResponseRedirect('/tdm/login')

    #get the city/jxd list
    city = city.encode('utf-8')
    venue = venue.encode('utf-8')
    dev = dev.encode('utf-8')
    #print [city, venue, ctmdev]

    #city_all = tmm.City.objects().order_by('zipcode')
    city_all = sorted(user_obj.station, key=lambda c:c.zipcode)
    if city == 'all':
        view_city = city_all[0] if len(city_all) > 0 else None
    if not city == 'all':
        view_city = tmm.City.objects(name=city).first()

    if not view_city in city_all:
        errors.append('您没有权限访问这个页面')
        return render_to_response('tdm_view_error_template.html', locals(), context_instance=RequestContext(request))

    view_venue = view_city.venues[0]
    if not venue == 'all':
        view_venue = tmm.Venue.objects(name=venue).first()
    srvdev_list = view_venue.server_devs

    nav_page = "server"
    return render_to_response('tdm_view_server_template.html', locals(), context_instance=RequestContext(request))


'''
------------------------------------------------------------------------------
[PAGE] server item detail web page
------------------------------------------------------------------------------
'''
def view_server_item_detail(request, city='all', venue='all', dev='all'):
    r = redis.Redis(host=tdm_redis_host, db=tdm_redis_db)
    errors = []
    result = []

    # cookies login
    login_ret, user_name, user_role = check_user_in_cookie(r, request, tdm_user_role_admin)
    print login_ret, user_name, user_role
    if login_ret == False:
        return HttpResponseRedirect('/tdm/login')

    #connect the database
    tmm.db_connect(tdm_mongo_acard_db)

    user_obj = tmm.TdmUser.objects(name=user_name).first()
    if not user_obj:
        return HttpResponseRedirect('/tdm/login')

    #get the city/jxd list
    city = city.encode('utf-8')
    venue = venue.encode('utf-8')
    dev = dev.encode('utf-8')

    #print [city, venue, ctmdev]

    #city_all = tmm.City.objects().order_by('zipcode')
    city_all = sorted(user_obj.station, key=lambda c:c.zipcode)
    if city == 'all':
        view_city = city_all[0] if len(city_all) > 0 else None
    if not city == 'all':
        view_city = tmm.City.objects(name=city).first()

    if not view_city in city_all:
        errors.append('您没有权限访问这个页面')
        return render_to_response('tdm_view_error_template.html', locals(), context_instance=RequestContext(request))

    view_venue = view_city.venues[0]
    if not venue == 'all':
        view_venue = tmm.Venue.objects(name=venue).first()

    nav_page = "server"
    return render_to_response('tdm_view_server_detail_template.html', locals(), context_instance=RequestContext(request))


'''
------------------------------------------------------------------------------
[PAGE] network view web page
------------------------------------------------------------------------------
'''
def view_network_item(request, city='all', venue='all', dev='all'):
    r = redis.Redis(host=tdm_redis_host, db=tdm_redis_db)
    errors = []
    result = []

    # cookies login
    login_ret, user_name, user_role = check_user_in_cookie(r, request, tdm_user_role_admin)
    print login_ret, user_name, user_role
    if login_ret == False:
        return HttpResponseRedirect('/tdm/login')
        
    #connect the database
    tmm.db_connect(tdm_mongo_acard_db)

    user_obj = tmm.TdmUser.objects(name=user_name).first()
    if not user_obj:
        return HttpResponseRedirect('/tdm/login')

    #get the city/jxd list
    city = city.encode('utf-8')
    venue = venue.encode('utf-8')
    dev = dev.encode('utf-8')

    #city_all = tmm.City.objects().order_by('zipcode')
    city_all = sorted(user_obj.station, key=lambda c:c.zipcode)
    if city == 'all':
        view_city = city_all[0] if len(city_all) > 0 else None
    if not city == 'all':
        view_city = tmm.City.objects(name=city).first()

    if not view_city in city_all:
        errors.append('您没有权限访问这个页面')
        return render_to_response('tdm_view_error_template.html', locals(), context_instance=RequestContext(request))

    view_venue = view_city.venues[0]
    if not venue == 'all':
        view_venue = tmm.Venue.objects(name=venue).first()
    netdev_list = view_venue.network_devs

    nav_page = "network"
    return render_to_response('tdm_view_network_template.html', locals(), context_instance=RequestContext(request))

'''
------------------------------------------------------------------------------
[PAGE] network item detail web page
------------------------------------------------------------------------------
'''
def view_network_item_detail(request, city='all', venue='all', dev='all'):
    r = redis.Redis(host=tdm_redis_host, db=tdm_redis_db)
    errors = []
    result = []

    # cookies login
    login_ret, user_name, user_role = check_user_in_cookie(r, request, tdm_user_role_admin)
    print login_ret, user_name, user_role
    if login_ret == False:
        return HttpResponseRedirect('/tdm/login')
        
    #connect the database
    tmm.db_connect(tdm_mongo_acard_db)

    user_obj = tmm.TdmUser.objects(name=user_name).first()
    if not user_obj:
        return HttpResponseRedirect('/tdm/login')

    #get the city/jxd list
    city = city.encode('utf-8')
    venue = venue.encode('utf-8')
    dev = dev.encode('utf-8')

    #city_all = tmm.City.objects().order_by('zipcode')
    city_all = sorted(user_obj.station, key=lambda c:c.zipcode)
    if city == 'all':
        view_city = city_all[0] if len(city_all) > 0 else None
    if not city == 'all':
        view_city = tmm.City.objects(name=city).first()

    if not view_city in city_all:
        errors.append('您没有权限访问这个页面')
        return render_to_response('tdm_view_error_template.html', locals(), context_instance=RequestContext(request))

    view_venue = view_city.venues[0]
    if not venue == 'all':
        view_venue = tmm.Venue.objects(name=venue).first()

    nav_page = "network"
    return render_to_response('tdm_view_network_detail_template.html', locals(), context_instance=RequestContext(request))


'''
------------------------------------------------------------------------------
[PAGE] mdm item web page
------------------------------------------------------------------------------
'''
def view_mdm_item(request, city='all', venue='all', classroom='all'):
    r = redis.Redis(host=tdm_redis_host, db=tdm_redis_db)
    errors = []
    result = []

    # cookies login
    login_ret, user_name, user_role = check_user_in_cookie(r, request, tdm_user_role_admin)
    print login_ret, user_name, user_role
    if login_ret == False:
        return HttpResponseRedirect('/tdm/login')
        
    #connect the database
    tmm.db_connect(tdm_mongo_acard_db)

    user_obj = tmm.TdmUser.objects(name=user_name).first()
    if not user_obj:
        return HttpResponseRedirect('/tdm/login')

    #get the city/jxd list
    city = city.encode('utf-8')
    venue = venue.encode('utf-8')
    classroom = classroom.encode('utf-8')

    #city_all = tmm.City.objects().order_by('zipcode')
    city_all = sorted(user_obj.station, key=lambda c:c.zipcode)
    if city == 'all':
        view_city = city_all[0] if len(city_all) > 0 else None
    if not city == 'all':
        view_city = tmm.City.objects(name=city).first()

    if not view_city in city_all:
        errors.append('您没有权限访问这个页面')
        return render_to_response('tdm_view_error_template.html', locals(), context_instance=RequestContext(request))

    view_venue = view_city.venues[0]
    if not venue == 'all':
        view_venue = tmm.Venue.objects(name=venue).first()
    classroom_list = view_venue.classroom_list

    nav_page = "mdm"
    return render_to_response('tdm_view_mdm_template.html', locals(), context_instance=RequestContext(request))

'''
------------------------------------------------------------------------------
[PAGE] mdm item detail web page
------------------------------------------------------------------------------
'''
def view_mdm_item_detail(request, city='all', venue='all', classroom='all'):
    r = redis.Redis(host=tdm_redis_host, db=tdm_redis_db)
    errors = []
    result = []

    # cookies login
    login_ret, user_name, user_role = check_user_in_cookie(r, request, tdm_user_role_admin)
    print login_ret, user_name, user_role
    if login_ret == False:
        return HttpResponseRedirect('/tdm/login')

    #connect the database
    tmm.db_connect(tdm_mongo_acard_db)

    user_obj = tmm.TdmUser.objects(name=user_name).first()
    if not user_obj:
        return HttpResponseRedirect('/tdm/login')

    #get the city/jxd list
    city = city.encode('utf-8')
    venue = venue.encode('utf-8')
    classroom = classroom.encode('utf-8')

    #city_all = tmm.City.objects().order_by('zipcode')
    city_all = sorted(user_obj.station, key=lambda c:c.zipcode)
    if city == 'all':
        view_city = city_all[0] if len(city_all) > 0 else None
    if not city == 'all':
        view_city = tmm.City.objects(name=city).first()

    if not view_city in city_all:
        errors.append('您没有权限访问这个页面')
        return render_to_response('tdm_view_error_template.html', locals(), context_instance=RequestContext(request))

    view_venue = view_city.venues[0]
    if not venue == 'all':
        view_venue = tmm.Venue.objects(name=venue).first()

    nav_page = "mdm"
    return render_to_response('tdm_view_mdm_detail_template.html', locals(), context_instance=RequestContext(request))

'''
------------------------------------------------------------------------------
[PAGE] mdm acard web page
------------------------------------------------------------------------------
'''
def _view_acard_item(request, city='all', venue='all'):
    r = redis.Redis(host=tdm_redis_host, db=tdm_redis_db)
    errors = []
    result = []

    # cookies login
    login_ret, user_name, user_role = check_user_in_cookie(r, request, tdm_user_role_admin)
    #print login_ret, user_name, user_role
    if login_ret == False:
        return HttpResponseRedirect('/tdm/login')

    #connect the database
    tmm.db_connect(tdm_mongo_acard_db)

    user_obj = tmm.TdmUser.objects(name=user_name).first()
    if not user_obj:
        return HttpResponseRedirect('/tdm/login')

    #city_all = tmm.City.objects().order_by('zipcode')
    city_all = sorted(user_obj.station, key=lambda c:c.zipcode)
    if city == 'all':
        view_city = city_all[0] if len(city_all) > 0 else None
    if not city == 'all':
        view_city = tmm.City.objects(name=city).first()

    if not view_city in city_all:
        errors.append('您没有权限访问这个页面')
        return render_to_response('tdm_view_error_template.html', locals(), context_instance=RequestContext(request))

    view_venue_ctmdev_list = []
    for venue in view_city.venues:
        #print 'venue:', venue.name
        if venue.disabled:
            continue
        for ctmdev in venue.ctm_devs:
            venue_log = {
                'venue': venue.name,
                'ctmdev': ctmdev.devid
            }
            view_venue_ctmdev_list.append(venue_log)
    view_venue_ctmdev_list = sorted(view_venue_ctmdev_list, key=lambda v:v['ctmdev'])

    nav_page = "acard"
    return render_to_response('tdm_view_acard_template.html', locals(), context_instance=RequestContext(request))

def view_acard_item(request, city='all', venue='all'):
    try:
        return _view_acard_item(request, city, venue)
    except Exception as e:
        err_msg = '(server error):%s' % str(e)
        print err_msg
        return HttpResponseServerError(err_msg)

'''
------------------------------------------------------------------------------
[PAGE] mdm acard detail web page
------------------------------------------------------------------------------
'''
def _view_acard_item_detail(request, city='all', venue='all', ctmdev='all'):
    r = redis.Redis(host=tdm_redis_host, db=tdm_redis_db)
    errors = []
    result = []

    # cookies login
    login_ret, user_name, user_role = check_user_in_cookie(r, request, tdm_user_role_admin)
    #print login_ret, user_name, user_role
    if login_ret == False:
        return HttpResponseRedirect('/tdm/login')

    #connect the database
    tmm.db_connect(tdm_mongo_acard_db)

    user_obj = tmm.TdmUser.objects(name=user_name).first()
    if not user_obj:
        return HttpResponseRedirect('/tdm/login')

    #get the city/venue list
    city = city.encode('utf-8')
    venue = venue.encode('utf-8')
    ctmdev = ctmdev.encode('utf-8')

    #city_all = tmm.City.objects().order_by('zipcode')
    city_all = sorted(user_obj.station, key=lambda c:c.zipcode)
    if city == 'all':
        view_city = city_all[0] if len(city_all) > 0 else None
    if not city == 'all':
        view_city = tmm.City.objects(name=city).first()

    if not view_city in city_all:
        errors.append('您没有权限访问这个页面')
        return render_to_response('tdm_view_error_template.html', locals(), context_instance=RequestContext(request))

    view_venue = view_city.venues[0]
    if not venue == 'all':
        view_venue = tmm.Venue.objects(name=venue).first()
    view_ctmdev = tmm.CtmDevice.objects(devid=ctmdev).first()
    venue_ctmdev_list = []
    for venue_obj in view_city.venues:
        for ctmdev_obj in venue_obj.ctm_devs:
            venue_ctmdev_list.append((venue_obj.name, ctmdev_obj.devid))
    #venue_log = tmm.AcardCtmLog.objects(ctm=ctmobj, class_date__gte=datetime.date.today()).order_by("-class_date")

    nav_page = "acard"
    return render_to_response('tdm_view_acard_detail_template.html', locals(), context_instance=RequestContext(request))

def view_acard_item_detail(request, city='all', venue='all', ctmdev='all'):
    try:
        return _view_acard_item_detail(request, city, venue, ctmdev)
    except Exception as e:
        err_msg = '(server error):%s' % str(e)
        print err_msg
        return HttpResponseServerError(err_msg)


'''
------------------------------------------------------------------------------
[PAGE] tdm log web page
------------------------------------------------------------------------------
'''
def view_server_log(request):
    r = redis.Redis(host=tdm_redis_host, db=tdm_redis_db)
    errors = []
    result = []

    # cookies login
    login_ret, user_name, user_role = check_user_in_cookie(r, request, tdm_user_role_admin)
    #print login_ret, user_name, user_role
    if login_ret == False:
        return HttpResponseRedirect('/tdm/login')

    #connect the database
    tmm.db_connect(tdm_mongo_acard_db)

    user_obj = tmm.TdmUser.objects(name=user_name).first()
    if not user_obj:
        return HttpResponseRedirect('/tdm/login')

    req_time = request.GET.get('req_time', '').encode('utf-8')
    req_module = request.GET.get('req_module', '').encode('utf-8')
    req_city = request.GET.get('req_city', '').encode('utf-8')
    req_venue = request.GET.get('req_venue', '').encode('utf-8')
    req_dev = request.GET.get('req_dev', '').encode('utf-8')
    req_item = request.GET.get('req_item', '').encode('utf-8')
    req_search = ''

    op = request.GET.get('op')
    if op == 'log_del':
        tmm.TdmLog.drop_collection()
    elif op == 'log_refresh':
        req_time = ''
        req_module = ''
        req_city = ''
        req_venue = ''
        req_dev = ''
        req_item = ''


    #按搜索条件检索日志
    #并且可以清除搜索条件
    search_time = None
    search_module = None
    search_city = None
    search_venue = None
    search_dev = None
    search_dict = {}

    if req_time:
        #2014/12/3 9:20
        if re.match(r'\d{4}/\d{1,2}/\d{1,2} \d{1,2}:\d{1,2}', req_time):
            search_time = datetime.strptime(req_time, '%Y/%m/%d %H:%M')
        #2014/12/3
        elif re.match(r'\d{4}/\d{1,2}/\d{1,2}', req_time):
            search_time = datetime.strptime(req_time, "%Y/%m/%d")
        #9:20
        elif re.match(r'\d+:\d+', req_time):
            search_time = datetime.strptime(datetime.date().strftime('%Y/%m/%d ') + req_time, '%Y/%m/%d %H:%M')
        search_dict['tm'] = {'$gt': search_time}
        req_search = req_search + '&%s=%s' % ('req_time', req_time)

    if req_module:
        search_module = tmm.TdmModule.objects(name=req_module).first()
        search_dict['module'] = search_module.id
        req_search = req_search + '&%s=%s' % ('req_module', req_module)

    if req_city:
        search_city = tmm.City.objects(name=req_city).first()
        search_dict['city'] = search_city.id
        req_search = req_search + '&%s=%s' % ('req_city', req_city)

    if req_venue:
        search_venue = tmm.Venue.objects(name=req_venue).first()
        search_dict['venue'] = search_venue.id
        req_search = req_search + '&%s=%s' % ('req_venue', req_venue)

    ser_log_per_page = 30 #每页10条日志
    ser_log_pg_start = 1
    ser_log_start = 0
    if request.method == 'GET':
        ser_log_pg_start = int(request.GET.get('log_start', '1'))
        ser_log_start = (ser_log_pg_start-1) * ser_log_per_page

    #ser_log_list = logs.find(search_dict).skip(ser_log_start).limit(ser_log_per_page).sort('_id', pymongo.DESCENDING)
    ser_log_list = tmm.TdmLog.objects(__raw__=search_dict).order_by('-tm')[ser_log_start:ser_log_start+ser_log_per_page]

    #总日志条数
    ser_log_len = tmm.TdmLog.objects(__raw__=search_dict).count()

    #总日志页数
    def ser_log_page_window(pg_start, pg_nr, pg_range):
        pg_wd_start, pg_wd_end = 1, pg_nr
        if pg_start - (pg_range / 2) > pg_wd_start:
            pg_wd_start = pg_start - (pg_range / 2)
        if pg_wd_start + pg_range < pg_nr:
            pg_wd_end = pg_wd_start + pg_range
        return range(pg_wd_start, pg_wd_end+1)
    ser_log_page_nr = ser_log_len / ser_log_per_page + (ser_log_len % ser_log_per_page == 0 and 0 or 1)
    ser_log_page_list = ser_log_page_window(ser_log_pg_start, ser_log_page_nr, 9)

    nav_page = "log"
    return render_to_response('tdm_view_warnlog_template.html', locals(), context_instance=RequestContext(request))

def view_tdm_report(request):
    return HttpResponseRedirect('/tdm/report/ctm_error/')

'''
------------------------------------------------------------------------------
[PAGE] tdm report ctm-error web page
------------------------------------------------------------------------------
'''
def view_tdm_report_ctm_error(request):
    r = redis.Redis(host=tdm_redis_host, db=tdm_redis_db)
    errors = []
    result = []

    # cookies login
    login_ret, user_name, user_role = check_user_in_cookie(r, request, tdm_user_role_admin)
    #print login_ret, user_name, user_role
    if login_ret == False:
        return HttpResponseRedirect('/tdm/login/')

    tmm.db_connect(tdm_mongo_acard_db)
    user_obj = tmm.TdmUser.objects(name=user_name).first()
    if not user_obj:
        return HttpResponseRedirect('/tdm/login/')

    #city_all = tmm.City.objects().order_by('zipcode')
    city_all = sorted(user_obj.station, key=lambda c:c.zipcode)

    city_select = request.POST.get('city_select','').encode('utf-8').strip()
    #start_date = request.POST.get('start_date','')
    #end_date = request.POST.get('end_date','')

    if not city_select:
        view_city = city_all[0] if len(city_all) > 0 else None
    else:
        view_city = tmm.City.objects(name=city_select).first()

    nav_page = "report"
    report_page = "ctm_error_rate"
    return render_to_response('tdm_view_report_ctm_error_template.html', locals(), context_instance=RequestContext(request))

'''
------------------------------------------------------------------------------
[PAGE] tdm report credit-card-rate web page
------------------------------------------------------------------------------
'''
def view_tdm_report_credit_card(request):
    r = redis.Redis(host=tdm_redis_host, db=tdm_redis_db)
    errors = []
    result = []

    # cookies login
    login_ret, user_name, user_role = check_user_in_cookie(r, request, tdm_user_role_admin)
    #print login_ret, user_name, user_role
    if login_ret == False:
        return HttpResponseRedirect('/tdm/login/')

    tmm.db_connect(tdm_mongo_acard_db)
    user_obj = tmm.TdmUser.objects(name=user_name).first()
    if not user_obj:
        return HttpResponseRedirect('/tdm/login/')

    #city_all = tmm.City.objects().order_by('zipcode')
    city_all = sorted(user_obj.station, key=lambda c:c.zipcode)

    city_select = request.POST.get('city_select','').encode('utf-8').strip()
    #start_date = request.POST.get('start_date','')
    #end_date = request.POST.get('end_date','')

    if not city_select:
        view_city = city_all[0] if len(city_all) > 0 else None
    else:
        view_city = tmm.City.objects(name=city_select).first()

    nav_page = "report"
    report_page = "credit_card_rate"
    return render_to_response('tdm_view_report_credit_card_template.html', locals(), context_instance=RequestContext(request))

'''
------------------------------------------------------------------------------
[PAGE] TDM admin main web page
------------------------------------------------------------------------------
'''
def tdm_admin(request):
    return HttpResponseRedirect('/tdm/admin/city')


'''
------------------------------------------------------------------------------
[PAGE] city admin main web page
------------------------------------------------------------------------------
'''
def tdm_admin_city(request):
    r = redis.Redis(host=tdm_redis_host, db=tdm_redis_db)
    errors = []
    result = []

    # cookies login
    login_ret, user_name, user_role = check_user_in_cookie(r, request, tdm_user_role_admin)
    print login_ret, user_name, user_role
    if login_ret == False:
        return HttpResponseRedirect('/tdm/login')

    if not user_role:
        return HttpResponseRedirect('/tdm/main')

    tmm.db_connect(tdm_mongo_acard_db)

    user_obj = tmm.TdmUser.objects(name=user_name).first()
    if not user_obj:
        return HttpResponseRedirect('/tdm/login')

    city_all = tmm.City.objects().order_by('zipcode')

    op = request.POST.get('op')
    if op == 'city_add':
        city = request.POST.get('city','').encode('utf-8').strip()
        zipcode = request.POST.get('zipcode', '').encode('utf-8').strip()
        city_obj = tmm.City.objects(name=city).first()
        if not city_obj:
            try:
                city_obj = tmm.City(name=city, zipcode=zipcode).save()
                result.append("城市 %s 添加成功" % city)
            except Exception as e:
                errors.append("添加城市 %s 失败: %s" % (city, str(e)))
        else:
            errors.append("城市 %s 已经存在" % (city,))
    elif op == 'city_del':
        city_list = request.POST.getlist('city')
        for city in city_list:
            city_obj = tmm.City.objects(name=city.encode('utf-8')).first()
            try:
                for user in tmm.TdmUser.objects(station=city_obj):
                    user.station.remove(city_obj)
                    user.save()
                city_obj.delete()
                result.append("城市 %s 删除成功" % city)
            except Exception as e:
                errors.append("删除城市 %s 失败: %s" % (city, str(e)))

    nav_page = "admin"
    admin_page = 'admin_city'
    #print errors
    return render_to_response('tdm_admin_city_template.html', locals(), context_instance=RequestContext(request))


'''
------------------------------------------------------------------------------
[PAGE] venue admin main web page
------------------------------------------------------------------------------
'''
def tdm_admin_venue(request, city='all'):
    r = redis.Redis(host=tdm_redis_host, db=tdm_redis_db)
    errors = []
    result = []

    # cookies login
    login_ret, user_name, user_role = check_user_in_cookie(r, request, tdm_user_role_admin)
    if login_ret == False:
        return HttpResponseRedirect('/tdm/login')

    if not user_role:
        return HttpResponseRedirect('/tdm/main')

    tmm.db_connect(tdm_mongo_acard_db)

    user_obj = tmm.TdmUser.objects(name=user_name).first()
    if not user_obj:
        return HttpResponseRedirect('/tdm/login')

    op = request.POST.get('op')
    if op == 'venue_add':
        city = request.POST.get('city', '').encode('utf-8').strip()
        venue = request.POST.get('venue','').encode('utf-8').strip()
        service_name = request.POST.get('service_name', '').encode('utf-8').strip()
        venue_id = request.POST.get('venue_id', '').encode('utf-8').strip()
        city_obj = tmm.City.objects(name=city).first()
        venue_obj = tmm.Venue.objects(venue_id=venue_id).first()
        try:
            if not venue_obj:
                venue_obj = tmm.Venue(name=venue, service_name=service_name, venue_id=venue_id, disabled=False).save()
                city_obj.venues.append(venue_obj)
                city_obj.save()
                result.append("教学点 %s 添加成功" % venue_obj.name)
            else:
                venue_obj.name = venue
                venue_obj.service_name = service_name
                venue_obj.save()
                result.append("教学点 %s 更新成功" % venue)
        except Exception as e:
            errors.append("添加教学点 %s 失败: %s" % (venue, str(e)))
    elif op == 'venue_del':
        venue_list = request.POST.getlist('venue_list')
        for venue_id in venue_list:
            try:
                #print 'venue_id', venue_id
                venue_obj = tmm.Venue.objects(venue_id=venue_id).first()
                city_obj = tmm.City.objects(venues=venue_obj).first()
                #print city_obj, venue_obj
                city_obj.venues.remove(venue_obj)
                city_obj.save()
                venue_obj.delete()
                #print city_obj.venues
                result.append("教学点 %s 删除成功" % venue_obj.name)
            except Exception as e:
                errors.append("教学点 %s 删除失败: %s" % (venue_id, str(e)))
    elif op == 'venue_disable':
        venue_list = request.POST.getlist('venue_list')
        for venue_id in venue_list:
            try:
                venue_obj = tmm.Venue.objects(venue_id=venue_id).first()
                city_obj = tmm.City.objects(venues=venue_obj).first()
                venue_obj.disabled = True
                venue_obj.save()
                # delete warn/alert key in redis
                # alert:acard:北京:盛方中心A座:010_shengfang_dm_r1_attend:online
                venue_alert_key = 'alert:acard:%s:%s:*' % (city_obj.name, venue_obj.name)
                for rds_key in r.keys(venue_alert_key):
                    r.delete(rds_key)
                venue_warn_key = 'warn:acard:%s:%s:*' % (city_obj.name, venue_obj.name)
                for rds_key in r.keys(venue_warn_key):
                    r.delete(rds_key)
                result.append("教学点 %s 停用成功" % venue_obj.name)
            except Exception as e:
                errors.append("教学点 %s 停用失败" % venue_obj.name)
    elif op == 'venue_enable':
        venue_list = request.POST.getlist('venue_list')
        for venue_id in venue_list:
            try:
                venue_obj = tmm.Venue.objects(venue_id=venue_id).first()
                venue_obj.disabled = False
                venue_obj.save()
                result.append("教学点 %s 启用成功" % venue_obj.name)
            except Exception as e:
                errors.append("教学点 %s 启用失败" % venue_obj.name)
    elif op == 'venuegroup_add':
        venue_list = request.POST.getlist('venue_list')
        city_obj = tmm.City.objects(name=city).first()
        try:
            vg_obj = tmm.VenueGroup()
            for venue_id in venue_list:
                venue_obj = tmm.Venue.objects(venue_id=venue_id).first()
                vg_obj.venues.append(venue_obj)
            vg_obj.save()
            city_obj.venuegroups.append(vg_obj)
            city_obj.save()
            result.append("教学点合并成功")
        except Exception as e:
            errors.append("教学点合并失败")
    elif op == 'venuegroup_del':
        vg_list = request.POST.getlist('vg_list')
        city_obj = tmm.City.objects(name=city).first()
        for vg_id in vg_list:
            try:
                vg_obj = tmm.VenueGroup.objects(id=vg_id).first()
                city_obj.venuegroups.remove(vg_obj)
                city_obj.save()
                vg_obj.delete()
                result.append("教学点解散成功")
            except Exception as e:
                errors.append("教学点解散失败")

    city_all = tmm.City.objects().order_by('zipcode')
    view_city = city_all.first()
    #print 'city:', city
    if not city == 'all':
        view_city = tmm.City.objects(name=city.encode('utf-8')).first()
    venue_all = view_city.venues
    venue_group_list = view_city.venuegroups

    nav_page = "admin"
    admin_page = 'admin_venue'
    #print errors
    return render_to_response('tdm_admin_venue_template.html', locals(), context_instance=RequestContext(request))

'''
------------------------------------------------------------------------------
[PAGE] admin power config web page
------------------------------------------------------------------------------
'''
def tdm_admin_power_cfg(request, city='all', venue='all'):
    r = redis.Redis(host=tdm_redis_host, db=tdm_redis_db)
    errors = []
    result = []

    # cookies login
    login_ret, user_name, user_role = check_user_in_cookie(r, request, tdm_user_role_admin)
    print login_ret, user_name, user_role
    if login_ret == False:
        return HttpResponseRedirect('/tdm/login')

    if not user_role:
        return HttpResponseRedirect('/tdm/main')

    tmm.db_connect(tdm_mongo_acard_db)

    user_obj = tmm.TdmUser.objects(name=user_name).first()
    if not user_obj:
        return HttpResponseRedirect('/tdm/login')

    nav_page = "admin"
    admin_page = 'admin_power'
    return render_to_response('tdm_admin_power_template.html', locals(), context_instance=RequestContext(request))

'''
------------------------------------------------------------------------------
[PAGE] admin network config web page
------------------------------------------------------------------------------
'''
def tdm_admin_network_cfg(request, city='all', venue='all'):
    r = redis.Redis(host=tdm_redis_host, db=tdm_redis_db)
    errors = []
    result = []

    # cookies login
    login_ret, user_name, user_role = check_user_in_cookie(r, request, tdm_user_role_admin)
    print login_ret, user_name, user_role
    if login_ret == False:
        return HttpResponseRedirect('/tdm/login')

    if not user_role:
        return HttpResponseRedirect('/tdm/main')

    tmm.db_connect(tdm_mongo_acard_db)

    user_obj = tmm.TdmUser.objects(name=user_name).first()
    if not user_obj:
        return HttpResponseRedirect('/tdm/login')

    op = request.POST.get('op')
    if op == "netdev_add":
        venue_id = request.POST.get('venue_id', '').encode('utf-8').strip()
        devid = request.POST.get('devid', '').encode('utf-8').strip()
        ip = request.POST.get('ip', '').encode('utf-8').strip()
        port_nr = request.POST.get('port_nr', '').encode('utf-8').strip()
        dev_type = request.POST.get('dev_type', '').encode('utf-8').strip()
        location = request.POST.get('location', '').encode('utf-8').strip()
        memo = request.POST.get('memo', '').encode('utf-8').strip()
        venue_obj = tmm.Venue.objects(venue_id=venue_id).first()
        netdev_obj = tmm.NetDevice.objects(devid=devid).first()
        if not netdev_obj:
            try:
                netdev_obj = tmm.NetDevice(devid=devid, ip=ip, port_nr=port_nr, dev_type=dev_type, location=location, memo=memo)
                netdev_obj.save()
                venue_obj.network_devs.append(netdev_obj)
                result.append("添加网络设备成功")
                venue_obj.save()
            except Exception as e:
                errors.append("添加网络设备 %s 失败: %s" % (netdev_obj.devid, str(e)))
        else:
            errors.append("网络设备 %s 已经存在" % (netdev_obj.devid,))
    elif op == "netdev_del":
        venue_id = request.POST.get('venue_id', '').encode('utf-8')
        netdev_list = request.POST.getlist('netdev_list')
        venue_obj = tmm.Venue.objects(venue_id=venue_id).first()
        for netdev_id in netdev_list:
            try:
                netdev_obj = tmm.NetDevice.objects(devid=netdev_id).first()
                venue_obj.network_devs.remove(netdev_obj)
                venue_obj.save()
                netdev_obj.delete()
                result.append("网络设备 %s 删除成功" % netdev_id)
            except Exception as e:
                errors.append("网络设备 %s 删除失败: %s" % (netdev_id, str(e)))

    city_all = tmm.City.objects().order_by('zipcode')
    view_city = city_all.first()
    if not city == 'all':
        view_city = tmm.City.objects(name=city.encode('utf-8')).first()
    view_venue = view_city.venues[0] if len(view_city.venues) > 0 else None
    if not venue == 'all':
        view_venue = tmm.Venue.objects(name=venue.encode('utf-8')).first()
    venue_all = view_city.venues
    netdev_all = view_venue.network_devs

    nav_page = "admin"
    admin_page = 'admin_network'
    return render_to_response('tdm_admin_network_template.html', locals(), context_instance=RequestContext(request))

'''
------------------------------------------------------------------------------
[PAGE] admin server config web page
------------------------------------------------------------------------------
'''
def tdm_admin_server_cfg(request, city='all', venue='all'):
    r = redis.Redis(host=tdm_redis_host, db=tdm_redis_db)
    errors = []
    result = []

    # cookies login
    login_ret, user_name, user_role = check_user_in_cookie(r, request, tdm_user_role_admin)
    print login_ret, user_name, user_role
    if login_ret == False:
        return HttpResponseRedirect('/tdm/login')

    if not user_role:
        return HttpResponseRedirect('/tdm/main')

    tmm.db_connect(tdm_mongo_acard_db)

    user_obj = tmm.TdmUser.objects(name=user_name).first()
    if not user_obj:
        return HttpResponseRedirect('/tdm/login')

    op = request.POST.get('op')
    if op == "srvdev_add":
        venue_id = request.POST.get('venue_id', '').encode('utf-8').strip()
        devid = request.POST.get('devid', '').encode('utf-8').strip()
        ip = request.POST.get('ip', '').encode('utf-8').strip()
        hostname = request.POST.get('hostname', '').encode('utf-8').strip()
        dev_type = request.POST.get('dev_type', '').encode('utf-8').strip()
        location = request.POST.get('location', '').encode('utf-8').strip()
        memo = request.POST.get('memo', '').encode('utf-8').strip()
        venue_obj = tmm.Venue.objects(venue_id=venue_id).first()
        srvdev_obj = tmm.SrvDevice.objects(devid=devid).first()
        if not srvdev_obj:
            try:
                srvdev_obj = tmm.SrvDevice(devid=devid, ip=ip, hostname=hostname, dev_type=dev_type, location=location, memo=memo)
                srvdev_obj.save()
                venue_obj.server_devs.append(srvdev_obj)
                result.append("添加服务器成功")
                venue_obj.save()
            except Exception as e:
                errors.append("添加服务器 %s 失败: %s" % (srvdev_obj.devid, str(e)))
        else:
            errors.append("服务器 %s 已经存在" % (srvdev_obj.devid,))
    elif op == "srvdev_del":
        venue_id = request.POST.get('venue_id', '').encode('utf-8')
        srvdev_list = request.POST.getlist('srvdev_list')
        venue_obj = tmm.Venue.objects(venue_id=venue_id).first()
        for srvdev_id in srvdev_list:
            try:
                srvdev_obj = tmm.SrvDevice.objects(devid=srvdev_id).first()
                venue_obj.server_devs.remove(srvdev_obj)
                venue_obj.save()
                srvdev_obj.delete()
                result.append("服务器 %s 删除成功" % srvdev_id)
            except Exception as e:
                errors.append("服务器 %s 删除失败: %s" % (srvdev_id, str(e)))

    city_all = tmm.City.objects().order_by('zipcode')
    view_city = city_all.first()
    if not city == 'all':
        view_city = tmm.City.objects(name=city.encode('utf-8')).first()
    view_venue = view_city.venues[0] if len(view_city.venues) > 0 else None
    if not venue == 'all':
        view_venue = tmm.Venue.objects(name=venue.encode('utf-8')).first()
    venue_all = view_city.venues
    srvdev_all = view_venue.server_devs

    nav_page = "admin"
    admin_page = 'admin_server'
    return render_to_response('tdm_admin_server_template.html', locals(), context_instance=RequestContext(request))

'''
------------------------------------------------------------------------------
[PAGE] admin mdm config web page
------------------------------------------------------------------------------
'''
def tdm_admin_mdm_cfg(request, city='all', venue='all'):
    r = redis.Redis(host=tdm_redis_host, db=tdm_redis_db)
    errors = []
    result = []

    # cookies login
    login_ret, user_name, user_role = check_user_in_cookie(r, request, tdm_user_role_admin)
    print login_ret, user_name, user_role
    if login_ret == False:
        return HttpResponseRedirect('/tdm/login')

    if not user_role:
        return HttpResponseRedirect('/tdm/main')

    tmm.db_connect(tdm_mongo_acard_db)

    user_obj = tmm.TdmUser.objects(name=user_name).first()
    if not user_obj:
        return HttpResponseRedirect('/tdm/login')

    nav_page = "admin"
    admin_page = 'admin_mdm'
    return render_to_response('tdm_admin_mdm_template.html', locals(), context_instance=RequestContext(request))

'''
------------------------------------------------------------------------------
[PAGE] admin acard config web page
------------------------------------------------------------------------------
'''
def tdm_admin_acard_cfg(request, city='all', venue='all'):
    r = redis.Redis(host=tdm_redis_host, db=tdm_redis_db)
    errors = []
    result = []

    # cookies login
    login_ret, user_name, user_role = check_user_in_cookie(r, request, tdm_user_role_admin)
    #print login_ret, user_name, user_role
    if login_ret == False:
        return HttpResponseRedirect('/tdm/login')
    if not user_role:
        return HttpResponseRedirect('/tdm/main')

    tmm.db_connect(tdm_mongo_acard_db)

    user_obj = tmm.TdmUser.objects(name=user_name).first()
    if not user_obj:
        return HttpResponseRedirect('/tdm/login')

    op = request.POST.get('op')
    if op == 'ctmdev_add':
        venue_id = request.POST.get('venue_id', '').encode('utf-8').strip()
        ctmdev_id = request.POST.get('ctmdev_id', '').encode('utf-8').strip()
        ctmdev_memo = request.POST.get('ctmdev_memo', '').encode('utf-8').strip()
        venue_obj = tmm.Venue.objects(venue_id=venue_id).first()
        ctmdev_obj = tmm.CtmDevice.objects(devid=ctmdev_id).first()
        if not ctmdev_obj:
            try:
                ctmdev_obj = tmm.CtmDevice(devid=ctmdev_id, memo=ctmdev_memo).save()
                venue_obj.ctm_devs.append(ctmdev_obj)
                venue_obj.save()
                result.append("中控机 %s 添加成功" % ctmdev_obj.devid)
            except Exception as e:
                errors.append("添加中控机 %s 失败: %s" % (ctmdev_id, str(e)))
        else:
            ctmdev_obj.memo = ctmdev_memo
            ctmdev_obj.save()
            result.append("中控机 %s 更新成功" % ctmdev_obj.devid)
    elif op == 'ctmdev_del':
        ctmdev_list = request.POST.getlist('ctmdev_list')
        venue_id = request.POST.get('venue_id', '').encode('utf-8').strip()
        venue_obj = tmm.Venue.objects(venue_id=venue_id).first()
        for ctmdev_id in ctmdev_list:
            try:
                ctmdev_obj = tmm.CtmDevice.objects(devid=ctmdev_id).first()
                venue_obj.ctm_devs.remove(ctmdev_obj)
                venue_obj.save()
                ctmdev_obj.delete()
                result.append("中控机 %s 删除成功" % ctmdev_obj.devid)
            except Exception as e:
                errors.append("中控机 %s 删除失败: %s" % (ctmdev_id, str(e)))
    elif op == 'cardreader_add':
        venue_id = request.POST.get('venue_id', '').encode('utf-8').strip()
        cardreader_ip = request.POST.get('cardreader_ip', '').encode('utf-8').strip()
        try:
            cardreader_obj = tmm.CardReader(ip=cardreader_ip)
            venue_obj = tmm.Venue.objects(venue_id=venue_id).first()
            venue_obj.card_readers.append(cardreader_obj)
            venue_obj.save()
            result.append("读卡器 %s 添加成功" % cardreader_ip)
        except Exception as e:
            errors.append("读卡器 %s 添加失败: %s" % (cardreader_ip, str(e)))

    elif op == 'cardreader_del':
        cardreader_list = request.POST.getlist('cardreader_list')
        venue_id = request.POST.get('venue_id', '').encode('utf-8').strip()
        venue_obj = tmm.Venue.objects(venue_id=venue_id).first()
        for cardreader_ip in cardreader_list:
            try:
                cardreader_obj = tmm.CardReader(ip=cardreader_ip)
                venue_obj.card_readers.remove(cardreader_obj)
                venue_obj.save()
                result.append("读卡器 %s 删除成功" % cardreader_ip)
            except Exception as e:
                errors.append("读卡器 %s 删除失败: %s" % (cardreader_ip, str(e)))

    city_all = tmm.City.objects().order_by('zipcode')
    view_city = city_all.first()
    if not city == 'all':
        view_city = tmm.City.objects(name=city.encode('utf-8')).first()
    view_venue = view_city.venues[0] if len(view_city.venues) > 0 else None
    if not venue == 'all':
        view_venue = tmm.Venue.objects(name=venue.encode('utf-8')).first()
    venue_all = view_city.venues
    ctmdev_all = view_venue.ctm_devs
    cardreader_all = view_venue.card_readers

    nav_page = "admin"
    admin_page = 'admin_acard'
    return render_to_response('tdm_admin_acard_template.html', locals(), context_instance=RequestContext(request))

'''
------------------------------------------------------------------------------
[PAGE] tdm alert config web page
------------------------------------------------------------------------------
'''
def tdm_admin_alert_cfg(request):
    r = redis.Redis(host=tdm_redis_host, db=tdm_redis_db)
    errors = []
    result = []

    # cookies login
    login_ret, user_name, user_role = check_user_in_cookie(r, request, tdm_user_role_admin)
    print login_ret, user_name, user_role
    if login_ret == False:
        return HttpResponseRedirect('/tdm/login')
    if not user_role:
        return HttpResponseRedirect('/tdm/main')

    tmm.db_connect(tdm_mongo_acard_db)

    user_obj = tmm.TdmUser.objects(name=user_name).first()
    if not user_obj:
        return HttpResponseRedirect('/tdm/login')

    op = request.POST.get('op')
    if op == 'alert_config':
        alert_email = request.POST.get('alert_email','').encode('utf-8').strip()
        email_passwd = request.POST.get('email_passwd','').encode('utf-8').strip()
        email_send_list = [es.encode('utf-8') for es in request.POST.getlist('email_send_list')]
        alert_by_city = [es.encode('utf-8') for es in request.POST.getlist('alert_by_city')]
        #print [alert_email, email_user, email_passwd, email_send_list]

        if alert_email and email_passwd: #and email_user
            alert_cfg = tmm.TdmAlert.objects().first()
            if not alert_cfg:
                alert_cfg = tmm.TdmAlert(alert_mail_user=alert_email, alert_mail_pass=email_passwd)
            else:
                alert_cfg.alert_mail_user = alert_email
                alert_cfg.alert_mail_pass = email_passwd
            alert_cfg.save()
            result.append("告警配置成功")
        else:
            errors.append("所有字段不能为空")

        for mod_obj in tmm.TdmModule.objects():
            if mod_obj.name in email_send_list:
                mod_obj.alert_enable = True
            else:
                mod_obj.alert_enable = False
            if mod_obj.name in alert_by_city:
                mod_obj.alert_by_city = True
            else:
                mod_obj.alert_by_city = False
            #add/del officer to TdmModule
            officer_list = request.POST.getlist(mod_obj.name + '_officers')
            mod_obj.officers = []
            for officer_name in officer_list:
                user_obj = tmm.TdmUser.objects(name=officer_name).first()
                if user_obj:
                    mod_obj.officers.append(user_obj)
            mod_obj.save()
        result.append("修改告警配置列表成功")


    if op == 'email_test':
        alert_rcvtest_email = request.POST.get('alert_rcvtest_email','').encode('utf-8').strip()
        alert_cfg = tmm.TdmAlert.objects().first()
        if None in (alert_cfg, alert_rcvtest_email) or \
            '' in (alert_cfg, alert_rcvtest_email):
            errors.append("告警配置或测试邮箱不能为空")
        else:
            login = {
                'user': alert_cfg.alert_mail_user,
                'passwd': alert_cfg.alert_mail_pass,
            }
            mail = {
                'to_addr': alert_rcvtest_email.split(';'),
                'subject': 'TDM告警测试邮件',
                'content': '本邮件为TDM告警测试邮件，用以证明告警邮箱配置正确，无需回复。',
            }
            client_send(login, mail)
            result.append("发送测试邮件成功，请稍后查收邮件")

    alert_cfg = tmm.TdmAlert.objects().first()
    mod_list = tmm.TdmModule.objects()
    user_list = tmm.TdmUser.objects()

    nav_page = "admin"
    admin_page = 'admin_alert'
    return render_to_response('tdm_admin_alert_template.html', locals(), context_instance=RequestContext(request))

'''
------------------------------------------------------------------------------
[PAGE] tdm admin user config web page
------------------------------------------------------------------------------
'''
def tdm_admin_user_cfg(request):
    r = redis.Redis(host=tdm_redis_host, db=tdm_redis_db)
    errors = []
    result = []

    # cookies login
    login_ret, user_name, user_role = check_user_in_cookie(r, request, tdm_user_role_admin)
    print login_ret, user_name, user_role
    if login_ret == False:
        return HttpResponseRedirect('/tdm/login')

    if not user_role:
        return HttpResponseRedirect('/tdm/main')

    tmm.db_connect(tdm_mongo_acard_db)

    user_obj = tmm.TdmUser.objects(name=user_name).first()
    if not user_obj:
        return HttpResponseRedirect('/tdm/login')

    op = request.POST.get('op')
    if op == 'user_add':
        new_user = request.POST.get('new_user','').encode('utf-8').strip()
        user_pass = request.POST.get('new_password','').encode('utf-8').strip()
        user_mail = request.POST.get('new_email','').encode('utf-8').strip()
        user_phone = request.POST.get('new_phone', '').encode('utf-8').strip()
        user_role = request.POST.get('new_role','').encode('utf-8').strip()
        user_station = request.POST.getlist('new_station')
        #print [new_user, user_pass, user_mail, user_role]
        if None in (new_user, user_pass, user_mail, user_phone, user_role, ) or \
            '' in (new_user, user_pass, user_mail, user_phone, user_role, ):
            errors.append("所有字段不能为空")
        else:
            try:
                u = tmm.TdmUser.objects(name=new_user).first()
                if not u:
                    u = tmm.TdmUser(
                        name=new_user,
                        passwd_md5=hashlib.md5(user_pass).hexdigest(),
                        email=user_mail,
                        phone=user_phone,
                        grant=user_role)
                    for station in user_station:
                        city_obj = tmm.City.objects(zipcode=station).first()
                        if city_obj:
                            u.station.append(city_obj)
                    result.append("添加用户成功")
                    mail = {
                        'to_addr': [user_mail],
                        'subject': '电子考勤监控账号',
                        'content': tdm_new_user_email % (new_user, user_pass),
                    }
                    alert_cfg = tmm.TdmAlert.objects().first()
                    login = {
                        'user': alert_cfg.alert_mail_user,
                        'passwd': alert_cfg.alert_mail_pass
                    }
                    client_send(login, mail, None)
                else:
                    u.passwd_md5 = hashlib.md5(user_pass).hexdigest()
                    u.email = user_mail
                    u.phone = user_phone
                    u.grant = user_role
                    while len(u.station) > 0:
                        u.station.pop()
                    for station in user_station:
                        city_obj = tmm.City.objects(zipcode=station).first()
                        if city_obj:
                            u.station.append(city_obj)
                    result.append("修改用户成功")
                u.save()
            except Exception as e:
                errors.append("添加用户失败: " + str(e))
    elif op == 'user_del':
        del_user_list = request.POST.getlist('del_user','')
        if len(del_user_list) == 0:
            errors.append("必须选择一个用户")
        else:
            for uname in del_user_list:
                try:
                    u = tmm.TdmUser.objects(name=uname).first()
                    for mod in tmm.TdmModule.objects(officers=u):
                        mod.officers.remove(u)
                        mod.save()
                    u.delete()
                    result.append("删除用户 %s 成功" % (uname,))
                except Exception as e:
                    errors.append("删除用户失败: " + str(e))

    user_list = tmm.TdmUser.objects().order_by('name')
    city_all = tmm.City.objects().order_by('zipcode')

    nav_page = "admin"
    admin_page = 'admin_user'
    return render_to_response('tdm_admin_user_config_template.html', locals(), context_instance=RequestContext(request))


'''
------------------------------------------------------------------------------
[PAGE] tdm developer web page
------------------------------------------------------------------------------
'''
def tdm_admin_dev(request):
    r = redis.Redis(host=tdm_redis_host, db=tdm_redis_db)
    errors = []
    result = []

    # cookies login
    login_ret, user_name, user_role = check_user_in_cookie(r, request, tdm_user_role_admin)
    print login_ret, user_name, user_role
    if login_ret == False:
        return HttpResponseRedirect('/tdm/login')

    if not user_role:
        return HttpResponseRedirect('/tdm/main')

    tmm.db_connect(tdm_mongo_acard_db)

    user_obj = tmm.TdmUser.objects(name=user_name).first()
    if not user_obj:
        return HttpResponseRedirect('/tdm/login')

    op = request.POST.get('op')
    if op == 'prob_add':
        user_mail = request.POST.get('user_email').strip()
        user_prob = request.POST.get('problem').strip()
        if None in (user_mail, user_prob, ) or \
            '' in (user_mail, user_prob, ):
            errors.append("所有字段不能为空")
        else:
            prob_key = '%d_%s_0' % (int(time.time() * 1000), user_mail)     #time_usermail
            prob_info = user_prob                                           #message
            r.hset(tdm_redis_key_prob, prob_key, prob_info)
            result.append("问题单提交成功")

    dev_rev = os.popen('../../scripts/setlocalversion ../../').read().strip()
    dev_log_lines = os.popen('git log --pretty=format:"%h|%an|%ar|%s" --since=4.weeks').readlines()
    dev_log_list = []
    for _dev_log in dev_log_lines:
        rev, dev_user, commit_tm, commit_msg = _dev_log.strip().split('|')
        dev_log_dict = {}
        dev_log_dict['rev'] = rev
        dev_log_dict['dev_user'] = dev_user
        dev_log_dict['commit_tm'] = commit_tm
        dev_log_dict['commit_msg'] = commit_msg
        dev_log_list.append(dev_log_dict)

    problem_list = []
    prob_key_list = r.hkeys(tdm_redis_key_prob)
    prob_key_list.sort(reverse=True)
    for prob_key in prob_key_list:
        _prob = {}
        _prob['time'], _prob['mail'], _prob['fixup'] = prob_key.split('_')
        _prob['content'] = r.hget(tdm_redis_key_prob, prob_key)
        problem_list.append(_prob)

    nav_page = "admin"
    admin_page = 'admin_dev'
    return render_to_response('tdm_admin_dev_template.html', locals(), context_instance=RequestContext(request))


'''
------------------------------------------------------------------------------
[PAGE] tdm auto command web page
------------------------------------------------------------------------------
'''
def tdm_admin_autocmd(request):
    r = redis.Redis(host=tdm_redis_host, db=tdm_redis_db)
    errors = []
    result = []
    cmd_list = []
    issued_cmd_list = []
    # cookies login
    login_ret, user_name, user_role = check_user_in_cookie(r, request, tdm_user_role_admin)
    print login_ret, user_name, user_role
    if login_ret == False:
        return HttpResponseRedirect('/tdm/login')

    if not user_role:
        return HttpResponseRedirect('/tdm/main')

    tmm.db_connect(tdm_mongo_acard_db)

    user_obj = tmm.TdmUser.objects(name=user_name).first()
    if not user_obj:
        return HttpResponseRedirect('/tdm/login')

    city_all = tmm.City.objects().order_by('zipcode')

    op = request.POST.get('op')
    if op == 'autocmd_config':
        city_venue_list = request.POST.get('city_venues','').encode('utf-8').strip().split(', ')
        command = request.POST.get('command','').encode('utf-8').strip()
        print city_venue_list
        #print command
        for city_venue in city_venue_list:
            city, venue = city_venue.strip().split(":")
            venue_obj = tmm.Venue.objects(name=venue).first()
            for ctmdev_obj in venue_obj.ctm_devs:
                AcardSetAutoCommand(r, city, venue, ctmdev_obj.devid, command)
        return HttpResponse(json.dumps(city_venue_list, ensure_ascii=False), content_type='application/javascript')

    cmdkeys = '%s:*' % (tdm_redis_autocmd_save_prefix,)
    for key in r.keys(cmdkeys):
        _autocmd = {}
        _autocmd['name'] = key[len(tdm_redis_autocmd_save_prefix)+1:]
        _autocmd['command'] = r.get(key)
        cmd_list.append(_autocmd)

    cmdkey_issued = '%s:*' % (tdm_redis_autocmd_prefix,)
    for key in r.keys(cmdkey_issued):
        _autocmd = {}
        #autocmd:沈阳:和平北大街:024_hpbj_ds_r1_attend
        m = key.split(':')
        m[3] = m[3].find('_dm_') > 0 and '主机' or '备机'
        del(m[0])
        _autocmd['key'] = key
        _autocmd['name'] = ' '.join(m)
        _autocmd['command'] = r.get(key)
        issued_cmd_list.append(_autocmd)

    nav_page = "admin"
    admin_page = 'admin_autocmd'
    return render_to_response('tdm_admin_autocmd_template.html', locals(), context_instance=RequestContext(request))

'''
------------------------------------------------------------------------------
[PAGE] tdm auto_command web page add cmd
------------------------------------------------------------------------------
'''
def tdm_admin_autocmd_add(request):
    r = redis.Redis(host=tdm_redis_host, db=tdm_redis_db)
    errors = []
    result = []

    # cookies login
    login_ret, user_name, user_role = check_user_in_cookie(r, request, tdm_user_role_admin)
    print login_ret, user_name, user_role
    if login_ret == False:
        return HttpResponseRedirect('/tdm/login')

    if not user_role:
        return HttpResponseRedirect('/tdm/main')

    savename = request.POST.get('savename', '').encode('utf-8').strip()
    command = request.POST.get('command', '').encode('utf-8')
    cmdkey = '%s:%s' % (tdm_redis_autocmd_save_prefix, savename)
    print cmdkey
    r.set(cmdkey, command)
    return HttpResponse(json.dumps([cmdkey, command], ensure_ascii=False), content_type='application/javascript')

'''
------------------------------------------------------------------------------
[PAGE] tdm auto_command web page del cmd
------------------------------------------------------------------------------
'''
def tdm_admin_autocmd_del(request):
    r = redis.Redis(host=tdm_redis_host, db=tdm_redis_db)
    errors = []
    result = []

    # cookies login
    login_ret, user_name, user_role = check_user_in_cookie(r, request, tdm_user_role_admin)
    print login_ret, user_name, user_role
    if login_ret == False:
        return HttpResponseRedirect('/tdm/login')

    if not user_role:
        return HttpResponseRedirect('/tdm/main')

    req_cmd_key_list = request.POST.getlist('issued_key')
    for issued_key in req_cmd_key_list:
        print issued_key
        r.delete(issued_key)

    return HttpResponse(json.dumps(req_cmd_key_list, ensure_ascii=False), content_type='application/javascript')

'''
------------------------------------------------------------------------------
[PAGE] tdm auto_command web page list cmd
------------------------------------------------------------------------------
'''
def tdm_admin_autocmd_list(request):
    r = redis.Redis(host=tdm_redis_host, db=tdm_redis_db)
    errors = []
    result = []
    autocmd_list = []

    # cookies login
    login_ret, user_name, user_role = check_user_in_cookie(r, request, tdm_user_role_admin)
    print login_ret, user_name, user_role
    if login_ret == False:
        return HttpResponseRedirect('/tdm/login')

    if not user_role:
        return HttpResponseRedirect('/tdm/main')

    cmdkey = '%s:*' % (tdm_redis_autocmd_save_prefix,)
    for key in r.keys(cmdkey):
        _autocmd = {}
        _autocmd['name'] = key[len(tdm_redis_autocmd_save_prefix)+1:]
        _autocmd['command'] = r.get(key)
        autocmd_list.append(_autocmd)
    return HttpResponse(json.dumps(autocmd_list, ensure_ascii=False), content_type='application/javascript')

